package com.dl.mall.service.admin.impl;

import com.alibaba.fastjson.JSONObject;
import com.dl.mall.entity.Page;
import com.dl.mall.entity.user.Address;
import com.dl.mall.entity.user.Order;
import com.dl.mall.entity.vo.HistoryOrderVo;
import com.dl.mall.entity.vo.OrderCartVo;
import com.dl.mall.mapper.OrderMapper;
import com.dl.mall.service.admin.OrderService_admin;
import com.dl.mall.service.user.AddressService;
import com.dl.mall.utils.PageUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author DL
 * @create 2022-04-16 14:30
 */
@Service
public class OrderServiceImpl_admin implements OrderService_admin {

    @Resource
    private OrderMapper orderMapper;

    /**
     * 查询 条件 获得历史订单
     * @param jsonObject 条件
     * @return 历史订单信息
     */
    @Override
    public Page<HistoryOrderVo> getHistoryOrderInfoByCondition(JSONObject jsonObject) {
        JSONObject condition = jsonObject.getJSONObject("condition"); // 总条件

        String userId = condition.getString("userId");// 用户id

        JSONObject orderSate = condition.getJSONObject("orderSate"); // 要查询状态
        boolean unpaid = orderSate.getBooleanValue("unpaid");
        boolean paid = orderSate.getBooleanValue("paid");
        boolean cancel = orderSate.getBooleanValue("cancel");

        ArrayList<Integer> orderStateList = new ArrayList<>();// 状态id集合
        if (unpaid)orderStateList.add(0);
        if (paid)orderStateList.add(1);
        if (cancel)orderStateList.add(2);

        PageHelper.startPage(condition.getInteger("currentPage"), 10);

        condition.put("orderStateList", orderStateList);
        System.out.println("condition = " + condition);


        List<HashMap<String, Object>> list = orderMapper.queryHistoryOrderInfoByCondition(condition);
        ArrayList<HistoryOrderVo> historyOrderVoList = new ArrayList<>();
        list.forEach(item -> {
            HistoryOrderVo historyOrderVo = new HistoryOrderVo();
            historyOrderVo.setUserId((String) item.get("user_id"));

            historyOrderVo.setOrderId((String) item.get("order_id"));
            historyOrderVo.setTotalAmount((BigDecimal) item.get("total_amount"));
            historyOrderVo.setOrderState((Integer) item.get("order_state"));
            historyOrderVo.setCreateTime((Timestamp) item.get("create_time"));
            historyOrderVo.setUpdateTime((Timestamp) item.get("update_time"));

            String productIdStr = (String) item.get("product_id");
            String[] productArr = productIdStr.split(",");

            String specsImgStr = (String) item.get("specs_img");
            String[] specsImgArr = specsImgStr.split(",");

            String nameStr = (String) item.get("name");
            String[] nameArr = nameStr.split(",");

            String productSpecsStr = (String) item.get("product_specs");
            String[] productSpecsArr = productSpecsStr.split("-,");
            //System.out.println("productSpecsStr = " + productSpecsStr);
            //System.out.println("productSpecsArr = " + Arrays.toString(productSpecsArr));

            String priceStr = (String) item.get("price");
            String[] priceArr = priceStr.split(",");

            String totalStr = (String) item.get("total");
            String[] totalArr = totalStr.split(",");

            ArrayList<OrderCartVo> historyCartVoList = new ArrayList<>();
            for (int i = 0; i < productArr.length; i++) {
                OrderCartVo orderCartVo = new OrderCartVo();
                orderCartVo.setProductId(productArr[i]);
                orderCartVo.setSpecsImg(specsImgArr[i]);
                orderCartVo.setName(nameArr[i]);

                productSpecsArr[i] = productSpecsArr[i].replaceAll("-","");
                orderCartVo.setProductSpecs(productSpecsArr[i]);
                orderCartVo.setPrice(new BigDecimal(priceArr[i]));
                orderCartVo.setTotal(Integer.parseInt(totalArr[i]));
                historyCartVoList.add(orderCartVo);
                historyOrderVo.setHistoryCartVoList(historyCartVoList);
            }

            historyOrderVoList.add(historyOrderVo);
        });

        //historyOrderVoList.forEach(System.out::println);
        PageInfo<?> pageInfo = new PageInfo<>(list);

        Page<HistoryOrderVo> page = new Page<>();//分页对象，保存分页所有信息
        page.setTotal((int) pageInfo.getTotal());//设置数据总数
        page.setPageSize(pageInfo.getPageSize());//设置页面大小
        page.setTotalPage(pageInfo.getPages());//设置页面总数
        page.setCurrentPage(pageInfo.getPageNum());//设置当前页码
        page.setList( historyOrderVoList);//放入主体信息

        return page;
    }

    @Resource
    private AddressService addressService;

    /**
     * 根据 订单id 获得某订单信息
     * @param orderId 订单id
     * @return 订单+地址
     */
    @Override
    public List<Object> getOrderInfoById(String orderId) {
        ArrayList<Object> result = new ArrayList<>();

        HashMap<String, Object> map = orderMapper.queryHistoryOrderInfoById(orderId);
        HistoryOrderVo historyOrderVo = new HistoryOrderVo();
        historyOrderVo.setUserId((String) map.get("user_id"));
        historyOrderVo.setOrderId((String) map.get("order_id"));
        historyOrderVo.setAddressId((String) map.get("address_id"));

        historyOrderVo.setTotalAmount((BigDecimal) map.get("total_amount"));
        historyOrderVo.setOrderState((Integer) map.get("order_state"));
        historyOrderVo.setCreateTime((Timestamp) map.get("create_time"));
        historyOrderVo.setUpdateTime((Timestamp) map.get("update_time"));

        String productIdStr = (String) map.get("product_id");
        String[] productArr = productIdStr.split(",");

        String specsImgStr = (String) map.get("specs_img");
        String[] specsImgArr = specsImgStr.split(",");

        String nameStr = (String) map.get("name");
        String[] nameArr = nameStr.split(",");

        String productSpecsStr = (String) map.get("product_specs");
        String[] productSpecsArr = productSpecsStr.split("-,");

        String priceStr = (String) map.get("price");
        String[] priceArr = priceStr.split(",");

        String totalStr = (String) map.get("total");
        String[] totalArr = totalStr.split(",");

        ArrayList<OrderCartVo> historyCartVoList = new ArrayList<>();
        for (int i = 0; i < productArr.length; i++) {
            OrderCartVo orderCartVo = new OrderCartVo();
            orderCartVo.setProductId(productArr[i]);
            orderCartVo.setSpecsImg(specsImgArr[i]);
            orderCartVo.setName(nameArr[i]);

            productSpecsArr[i] = productSpecsArr[i].replaceAll("-","");
            orderCartVo.setProductSpecs(productSpecsArr[i]);
            orderCartVo.setPrice(new BigDecimal(priceArr[i]));
            orderCartVo.setTotal(Integer.parseInt(totalArr[i]));
            historyCartVoList.add(orderCartVo);
            historyOrderVo.setHistoryCartVoList(historyCartVoList);
        }

        Address address = addressService.getAddressById((String) map.get("address_id"));

        result.add(historyOrderVo);
        result.add(address);

        return result;
    }

    @Override
    public List<Order> getOrderList() {
        return orderMapper.queryOrderList();
    }

    @Override
    public List<Order> getOrderListByDay(Integer day) {
        List<Order> orderList = orderMapper.queryOrderListByDay(7);

/*        orderList.stream().collect(Collectors.groupingBy(Order::getCreateTime,Collectors.toList()))
                .forEach((age,fooListByName)->{
                    groupList.add(fooListByName);
                });*/

        return orderMapper.queryOrderListByDay(7);
    }


}
